package com.miniapp.service.impl;

import com.aliyun.oss.model.SimplifiedObjectMeta;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miniapp.constant.status.AttachmentStorageType;
import com.miniapp.dto.AttachmentDTO;
import com.miniapp.entity.MiniAttachmentEntity;
import com.miniapp.entity.enums.AttachmentFileType;
import com.miniapp.mapper.MiniAttachmentMapper;
import com.miniapp.service.MiniAttachmentService;
import com.miniapp.service.RemoteFileService;
import com.miniapp.utils.BaseUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.List;

/**
 * 附件
 */
@Service
public class MiniAttachmentServiceImpl extends BaseServiceImpl<MiniAttachmentMapper,MiniAttachmentEntity> implements MiniAttachmentService {

	@Autowired
    RemoteFileService remoteFileService;

	//cdn的域名
	@Value("${venice.cdn.domain.upload:}")
	private String uploadCdnDomain ="";

	@Override
	@Transactional
	public MiniAttachmentEntity createAttachment(String fileName, String saveFilePath, InputStream fileInputStream, String media, Long userId) {

		SimplifiedObjectMeta aliFile = remoteFileService.uploadToAliyun(saveFilePath,fileInputStream);
		MiniAttachmentEntity miniAttachment = new MiniAttachmentEntity();
		miniAttachment.setFilename(fileName);
		miniAttachment.setFileSize(aliFile.getSize()); //文件的大小
		miniAttachment.setFileUrl(saveFilePath);
		miniAttachment.setStorageType(AttachmentStorageType.ALIYUN.getValue());
		if (BaseUtils.isNotEmpty(userId)){
			miniAttachment.setUserId(userId);
		}
		if (BaseUtils.isNotEmpty(media)){
			if (media.equals("video")){
				miniAttachment.setFileType(AttachmentFileType.VIDEO);
			}
			if (media.equals("image")){
				miniAttachment.setFileType(AttachmentFileType.IMAGE);
			}
			if (media.equals("ue")){
				miniAttachment.setFileType(AttachmentFileType.IMAGE);
			}
		}
		baseMapper.insert(miniAttachment);
		return miniAttachment;
	}

	@Override
	public String getFullRequestUrl(MiniAttachmentEntity miniAttachment) {
		return getFullRequestUrl(miniAttachment,-1,-1);
	}

	@Override
	public String getFullRequestUrl(MiniAttachmentEntity miniAttachment, int width, int height) {
		if(AttachmentStorageType.LOCAL.getValue().equals(miniAttachment.getStorageType())){ //本地
			return uploadCdnDomain + miniAttachment.getFileUrl();
		}else if(AttachmentStorageType.REMOTE.getValue().equals(miniAttachment.getStorageType())){ //远程
			return miniAttachment.getFileUrl();
		}else if(AttachmentStorageType.ALIYUN.getValue().equals(miniAttachment.getStorageType())){ //阿里云
			StringBuilder sbResult = new StringBuilder(uploadCdnDomain);
			if(!StringUtils.startsWith(miniAttachment.getFileUrl(),"/")){
				sbResult.append("/");
			}
			sbResult.append(miniAttachment.getFileUrl());
			if(width>0 && height >0) {
				sbResult.append("?x-oss-process=image/resize,m_lfit,h_"+height+",w_"+width);
			}
			return sbResult.toString();
		}
		return miniAttachment.getFileUrl();
	}

	@Override
	public String upload(String originalFilename, String saveFilePath, InputStream inputStream) {
		remoteFileService.uploadToAliyun(saveFilePath,inputStream);
		return uploadCdnDomain+"/"+saveFilePath;
	}

	@Override
	public List<MiniAttachmentEntity> findByAttachmentDTO(AttachmentDTO attachmentDTO) {

		String month ="";
		if (BaseUtils.isNotEmpty(attachmentDTO.getMonth())&&!attachmentDTO.getMonth().equals("0")){
			attachmentDTO.getMonth();
			if (attachmentDTO.getMonth().length()==1){
				month = "0" + month;
			}
		}
		return  baseMapper.selectList(new QueryWrapper<MiniAttachmentEntity>()
				.eq(BaseUtils.isNotEmpty(attachmentDTO.getType()),"file_type",attachmentDTO.getType())
				.like(BaseUtils.isNotEmpty(attachmentDTO.getYear())&&!attachmentDTO.getYear().equals("0"),"create_time",attachmentDTO.getYear()+"-%")
				.eq(BaseUtils.isNotEmpty(attachmentDTO.getUserId()),"user_id",attachmentDTO.getUserId())
				.eq(BaseUtils.isNotEmpty(attachmentDTO.getMonth())&&!attachmentDTO.getMonth().equals("0"),"create_time","%-"+month+"-%")
		);
//		return baseMapper.findAll(new Specification<MiniAttachmentEntity>(){
//			@Override
//			public Predicate toPredicate(Root<MiniAttachmentEntity> root,
//										 CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
//				Predicate p1 = null;
//				if(BaseUtils.isNotEmpty(attachmentDTO.getType())) {
//					Predicate p2 = cb.equal(root.get("fileType").as(Integer.class),attachmentDTO.getType());
//					if(p1 != null) {
//						p1 = cb.and(p1,p2);
//					} else {
//						p1 = p2;
//					}
//				}
//
//				if(BaseUtils.isNotEmpty(attachmentDTO.getYear())&&!attachmentDTO.getYear().equals("0")) {
//					Predicate p2 = cb.like(root.get("createTime").as(String.class), attachmentDTO.getYear()+"-%");
//					if(p1 != null) {
//						p1 = cb.and(p1,p2);
//					} else {
//						p1 = p2;
//					}
//				}
//				if(BaseUtils.isNotEmpty(attachmentDTO.getUserId())) {
//					Predicate p2 = cb.equal(root.get("userId").as(Long.class), attachmentDTO.getUserId());
//					if(p1 != null) {
//						p1 = cb.and(p1,p2);
//					} else {
//						p1 = p2;
//					}
//				}
//				if(BaseUtils.isNotEmpty(attachmentDTO.getMonth())&&!attachmentDTO.getMonth().equals("0")) {
//					String month = attachmentDTO.getMonth();
//					if (attachmentDTO.getMonth().length()==1){
//						month = "0" + month;
//					}
//					Predicate p2 = cb.like(root.get("createTime").as(String.class), "%-"+month+"-%");
//					if(p1 != null) {
//						p1 = cb.and(p1,p2);
//					} else {
//						p1 = p2;
//					}
//				}
//				return p1;
//			}
//		});
	}
}
